import requests

import os
import sys
import django

sys.path.append("/home/ubuntu/pythonObject/ops_middleware")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ops_middleware.settings")
django.setup()

import requests
from huaweicloudsdkcore.auth.credentials import BasicCredentials
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkvpc.v2 import *
from huaweicloudsdkvpc.v2.region.vpc_region import VpcRegion
from api.models import CloudSecurityGroups, HuaWeiCloud
from rest_framework.exceptions import ValidationError
from api.extension import return_code
from rest_framework.response import Response


class HuaWeiCloudMiddleware(object):
    def __init__(self, app_ak, app_sk, app_region):
        self.ak = app_ak
        self.sk = app_sk
        self.region = app_region

    def create_vpc_client(self):
        # 创建VPC客户端连接
        credentials = BasicCredentials(self.ak, self.sk)
        client = VpcClient.new_builder().with_credentials(credentials=credentials).with_region(
            VpcRegion.value_of(self.region)).build()
        return client

    def create_security_group_rule(self, remote_ip_response, description, security_group_id, client):
        """
       创建安全组策略
       :param security_group_id: 安全组id
       :param description: 安全组规则备注参数
       :param remote_ip_response: 获取本地外网ip传入
       :return:
       """
        try:
            request = NeutronCreateSecurityGroupRuleRequest()
            securityGroupRuleNeutronCreateSecurityGroupRuleOption = NeutronCreateSecurityGroupRuleOption(
                description=description,
                direction="ingress",
                ethertype="IPv4",
                remote_ip_prefix=remote_ip_response.strip(),
                security_group_id=security_group_id)
            request.body = NeutronCreateSecurityGroupRuleRequestBody(
                security_group_rule=
                securityGroupRuleNeutronCreateSecurityGroupRuleOption)

            response = client.neutron_create_security_group_rule(request)
            return response
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)

    def list_security_group_rules_id(self, description, method=None):
        request = NeutronListSecurityGroupRulesRequest()
        request.description = description
        client = self.create_vpc_client()
        try:
            response = client.neutron_list_security_group_rules(request)
            if method.lower() == "put":
                if not response.security_group_rules:
                    return Response({"code": return_code.VALIDATE_ERROR, "error": "数据异常超出索引"})
                security_id = response.security_group_rules[0].id
                security_group_id = response.security_group_rules[0].security_group_id
                return security_id, security_group_id, client

        except exceptions.ClientRequestException as e:
            raise ValidationError({"code": e.status_code, "error": e.error_msg})

    def list_security_group_id(self):
        request = NeutronListSecurityGroupsRequest()
        request.name = "深思维"
        client = self.create_vpc_client()
        response = client.neutron_list_security_groups(request)
        security_group_id = response.security_groups[0].id
        return security_group_id, client

    def delete_security(self, security_id, client):
        try:
            request = NeutronDeleteSecurityGroupRuleRequest()
            request.security_group_rule_id = security_id
            response = client.neutron_delete_security_group_rule(request)
            return response
        except exceptions.ClientRequestException as e:
            raise ValidationError({"code": e.status_code, "error": e.error_msg})


if __name__ == '__main__':
    cloud_object = HuaWeiCloud.objects.filter(id=2).first()
    ak = cloud_object.cloud_ak
    sk = cloud_object.cloud_sk
    region = cloud_object.cloud_zone
    security_object = HuaWeiCloudMiddleware(ak, sk, region)
    description = "范雪飞"
    remote_ip_response = "1.1.1.2"
    security_id, security_group_id, client = security_object.list_security_group_rules_id(description)
    # security_object.delete_security(security_id=security_id, client=client)
    # security_object.create_security_group_rule(remote_ip_response,description,security_group_id, client)
